package it.fuesi.synoutils.activities;

import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.FragmentManager;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;

import it.fuesi.synoutils.R;
import it.fuesi.synoutils.fragments.BTSearchFragment;
import it.fuesi.synoutils.fragments.BaseFragment;
import it.fuesi.synoutils.fragments.DownloadStationFragment;
import it.fuesi.synoutils.fragments.EmuleSearchFragment;
import it.fuesi.synoutils.fragments.FileStationFragment;
import it.fuesi.synoutils.fragments.HomeFragment;
import it.fuesi.synoutils.fragments.NavigationDrawerFragment;
import it.fuesi.synoutils.model.config.SynoConfig;
import it.fuesi.synoutils.model.filestation.FileStationFile;
import it.fuesi.synoutils.services.cache.CacheService;
import it.fuesi.synoutils.services.client.ServiceClientFactory;


public class MainActivity extends Activity
        implements NavigationDrawerFragment.NavigationDrawerCallbacks, DownloadStationFragment.OnFragmentInteractionListener, FileStationFragment.OnFragmentInteractionListener, BTSearchFragment.OnFragmentInteractionListener, EmuleSearchFragment.OnFragmentInteractionListener, HomeFragment.OnFragmentInteractionListener {

    private static final String TAG = "MainActivity";

    private static final String PREF_VERSION_CODE = "VERSION_CODE";

    public static int APP_VERSION_CODE = 0;
    public static String APP_VERSION_STRING = "";

    /**
     * Fragment managing the behaviors, interactions and presentation of the navigation drawer.
     */
    private NavigationDrawerFragment mNavigationDrawerFragment;

    /**
     * Used to store the last screen title. For use in {@link #restoreActionBar()}.
     */
    private CharSequence mTitle;




    public BaseFragment getCurrentFragment(){
        return mCurrentFragment;
    }

    @Override
    public void onFragmentInteraction(Uri uri) {

    }

    @Override
    public void onBackPressed() {
       boolean managed =  mCurrentFragment.onBackPressed();
       if(!managed)super.onBackPressed();
    }


    private void checkVersionUpgrade(){
        try{
            PackageInfo packageInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
            APP_VERSION_CODE = packageInfo.versionCode;
            APP_VERSION_STRING = packageInfo.versionName;

            SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(this);

            if(!p.contains(PREF_VERSION_CODE)){
                p.edit().putInt(PREF_VERSION_CODE, APP_VERSION_CODE).commit();
                onVersionUpgrade();
            }else{
                int prefVersionCode = p.getInt(PREF_VERSION_CODE, APP_VERSION_CODE);

                if(APP_VERSION_CODE > prefVersionCode){
                    onVersionUpgrade();
                    p.edit().putInt(PREF_VERSION_CODE, APP_VERSION_CODE).commit();
                }
            }



        }catch(Exception e){
            Log.e(TAG, "checkVersionUpgrade --> ", e);
        }

    }

    private void onVersionUpgrade(){
        Log.d(TAG, "OnVersionUpgrade --> clearing cache");
        CacheService.clear(this);
    }

    private boolean checkSettings(){
        final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
        final SynoConfig config = SynoConfig.factory(prefs);

        Log.d(TAG, "Configuration isSet: " + config.isSet() + " - config: " + config.toString());

        if(!config.isSet()){
            confirmSettings();
            return false;
        }else
            ServiceClientFactory.setSynoConfig(config);

        return true;
    }

    private void confirmSettings(){
        new AlertDialog.Builder(this)
                .setTitle("Configuration not set")
                .setMessage("Would you like to configure your Synology DiskStation now?")
                .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                       doConfiguration();
                    }
                })
                .setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                })
                .setIcon(android.R.drawable.ic_dialog_alert)
                .show();
    }

    private void doConfiguration(){
        final Intent i = new Intent(this, SettingsActivity.class);
        startActivityForResult(i, SettingsActivity.REQUEST_CODE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        Log.d(TAG, "On Activity result --> requestCode:" + requestCode + " - resultCode:" + resultCode);

        if(requestCode == SettingsActivity.REQUEST_CODE){
            if(resultCode == RESULT_OK){
                final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
                final SynoConfig config = SynoConfig.factory(prefs);
                Log.d(TAG, "Configuration: " + config.toString());
                ServiceClientFactory.setSynoConfig(config);
            }else if(resultCode == SettingsActivity.RESULT_QUIT){
                quit();
            }
        }else if(requestCode == DownloadTaskDetailActivity.REQUEST_CODE){
            if(resultCode == RESULT_OK){
                mCurrentFragment.onActionRefresh();
            }
        }else if(requestCode == FileStationFileDetailActivity.REQUEST_CODE){
            if(resultCode == RESULT_OK){
                onRefresh();
            }
            if(resultCode == FileStationFileDetailActivity.RESULT_CODE_COPY){
                //final FileStationFile file = (FileStationFile)data.getSerializableExtra(FileStationFileDetailActivity.RESULT_EXTRA_FILE);
                //FileStationFragment fragment = (FileStationFragment)mCurrentFragment;
                //fragment.doCopy(file);
            }
        }
    }

    @Override
    protected void onStart() {
        super.onStart();


        final boolean isSet = checkSettings();
        Log.d(TAG, "onStart --> isSet: " + isSet);

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Log.d(TAG, "OnCreate -->");

        checkVersionUpgrade();

       // Log.d(TAG, "Clearing cache -->");
       // CacheService.clear(this);

        Log.d(TAG, "Setting content view -->");
        setContentView(R.layout.activity_main);

        Log.d(TAG, "Setting navigation drawer -->");
        mNavigationDrawerFragment = (NavigationDrawerFragment)
                getFragmentManager().findFragmentById(R.id.navigation_drawer);
        mTitle = getTitle();

        // Set up the drawer.
        mNavigationDrawerFragment.setUp(
                R.id.navigation_drawer,
                (DrawerLayout) findViewById(R.id.drawer_layout));


        checkIncomingIntent();


    }

    private void checkIncomingIntent(){
        Intent intent = getIntent();
        String action = intent.getAction();
        String type = intent.getType();

        if (Intent.ACTION_SEND.equals(action) && type != null) {
            if ("text/plain".equals(type))
                handleSendText(intent);
        }
    }

    private void handleSendText(Intent intent) {
        final String sharedText = cleanSharedText(intent.getStringExtra(Intent.EXTRA_TEXT));
        if (sharedText != null) {
            final EditText edit = new EditText(this);
            edit.setText(sharedText);
            new AlertDialog.Builder(this)
                    .setTitle("Incoming shared text")
                    .setView(edit)
                    .setMessage("Incoming search request:")
                    .setPositiveButton("BitTorrent", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            searchWithTorrent(edit.getText().toString());
                        }
                    })
                    .setNeutralButton("Emule", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            searchWithEmule(edit.getText().toString());
                        }
                    })
                    .setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    })
                    .setIcon(android.R.drawable.ic_dialog_alert)
                    .show();
        }
    }

    private String cleanSharedText(String s){
        if(s == null) return s;

        String finalString = "";
        int httpPosition = s.toUpperCase().indexOf("HTTP");

        if(httpPosition >= 0){
            char currentChar = 'H';
            int currentIndex = httpPosition;
            while(currentChar != ' ' && currentIndex < s.length()){
                currentChar = s.charAt(currentIndex);
                currentIndex++;
            }
            for(int i=0; i<httpPosition; i++)
                finalString += s.charAt(i);

            for(int i=currentIndex; i<s.length(); i++)
                finalString += s.charAt(i);
        }else
            finalString = s;

        finalString = finalString.replaceAll("Check out", "");
        finalString = finalString.replaceAll("Check-out", "");
        finalString = finalString.trim();

        final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
        final String prefix = prefs.getString("search_prefix", "");
        final String suffix = prefs.getString("search_suffix", "");
        finalString = prefix + finalString + suffix;


        return finalString;
    }

    private void searchWithTorrent(String keyword){
        mCurrentFragment = BTSearchFragment.newInstance(2, keyword);

        FragmentManager fragmentManager = getFragmentManager();
        fragmentManager.beginTransaction()
                .replace(R.id.container, mCurrentFragment)
                .commit();
    }

    private void searchWithEmule(String keyword){
        mCurrentFragment = EmuleSearchFragment.newInstance(3, keyword);

        FragmentManager fragmentManager = getFragmentManager();
        fragmentManager.beginTransaction()
                .replace(R.id.container, mCurrentFragment)
                .commit();
    }


    private BaseFragment mCurrentFragment;

    public void setCurrentFragment(BaseFragment frag){
        this.mCurrentFragment = frag;
    }




    @Override
    public void onNavigationDrawerItemSelected(int position) {
        // update the main content by replacing     fragments

        switch(position){
            case 0:
                mCurrentFragment = HomeFragment.newInstance(position);
            break;
            case 1:
                mCurrentFragment = DownloadStationFragment.newInstance(position);
            break;
            case 2:
                mCurrentFragment = BTSearchFragment.newInstance(position);
            break;
            case 3:
                mCurrentFragment = EmuleSearchFragment.newInstance(position);
            break;
            case 4:
                mCurrentFragment = FileStationFragment.newInstance(position);
            break;
            default:
                mCurrentFragment = null;
        }

        if(mCurrentFragment != null){
            FragmentManager fragmentManager = getFragmentManager();
            fragmentManager.beginTransaction()
                    .replace(R.id.container, mCurrentFragment)
                    .commit();
        }


    }

    public void onSectionAttached(int number) {
        Log.d(TAG, "OnSectionAttached --> " + number);

        switch (number) {
            case 0:
                mTitle = getString(R.string.title_section0);
                break;
            case 1:
                mTitle = getString(R.string.title_section1);
                break;
            case 2:
                mTitle = getString(R.string.title_section2);
                break;
            case 3:
                mTitle = getString(R.string.title_section3);
                break;
            case 4:
                mTitle = getString(R.string.title_section4);
                break;
        }
    }

    public void restoreActionBar() {
        ActionBar actionBar = getActionBar();
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
        actionBar.setDisplayShowTitleEnabled(true);
        actionBar.setTitle(mTitle);
    }

    private Menu mMenu;

    public Menu getMenu(){
        return this.mMenu;
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        if (!mNavigationDrawerFragment.isDrawerOpen()) {
            // Only show items in the action bar relevant to this screen
            // if the drawer is not showing. Otherwise, let the drawer
            // decide what to show in the action bar.
            if(mCurrentFragment.getClass() == DownloadStationFragment.class) {
                getMenuInflater().inflate(R.menu.download_station, menu);
            }else if(mCurrentFragment.getClass() == FileStationFragment.class){
                getMenuInflater().inflate(R.menu.file_station, menu);
            }else
                getMenuInflater().inflate(R.menu.main, menu);
            restoreActionBar();

            this.mMenu = menu;

            return true;
        }
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        boolean returnValue = mCurrentFragment.onOptionsItemSelected(item);
        if(returnValue) return true;
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            final Intent i = new Intent(this, SettingsActivity.class);
            startActivityForResult(i, SettingsActivity.REQUEST_CODE);

        }else if(id == R.id.action_refresh){
            mCurrentFragment.onActionRefresh();
        }else if(id == R.id.action_quit){
            quit();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    public void quit(){
        quit(null);
    }

    public void quit(View caller){
        new AlertDialog.Builder(this)
                .setTitle("Exit Synoutils")
                .setMessage("Do you really want to exit?")
                .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        finish();
                    }
                })
                .setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                })
                .setIcon(android.R.drawable.ic_dialog_alert)
                .show();

    }


    public void onRefresh(){
        mCurrentFragment.onActionRefresh();
    }






}
